package com.h819.core.web.struts2;

/**
 * 自定义数值验证器
 * 需要填入的数字为一个数值，包括整数和实数
 * 此正则表达式可以直接放入配置文件中,不必单独创建验证器
 * <!--  add by apollo, 2008.09.11 -->
 */

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

import java.util.regex.PatternSyntaxException;

public final class RegValidator extends FieldValidatorSupport {

	private boolean trim = true;

	public void validate(Object arg0) throws ValidationException {

		// 获得字段的名字
		String fieldName = getFieldName();
		// 获得输入界面输入的值
		String value = (String) this.getFieldValue(fieldName, arg0);

		if (trim) {
			value = value.trim();
		}

		try {
			
			boolean foundMatch = value.matches("[-+]?\\b[0-9]*\\.?[0-9]+\\b");
			
			if (!foundMatch) {
				addFieldError(fieldName, arg0);
			}
			
		} catch (PatternSyntaxException ex) {
			// Syntax error in the regular expression
		}

	}

	public boolean isTrim() {
		return trim;
	}

	public void setTrim(boolean trim) {
		this.trim = trim;
	}

}